#include "stdafx.h"
#include "writer.h"
#include <string>

#include "resource.h"
#include "ui_tagger.h"


typedef std::wstring tstring;


LRESULT CTaggerDialog::OnBnClickedButtonUpdate(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	// Updating
	static_api_ptr_t<metadb_io_v2>()->update_info_async(m_handles, new service_impl_t<tag_writter>(m_handles, m_strings, m_skipped), core_api::get_main_window(), metadb_io_v2::op_flag_delay_ui, NULL);
	DestroyWindow();

	return FALSE;
}

LRESULT CTaggerDialog::OnLvnItemchangedListFiles(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
	LPNMLISTVIEW pnmv = (LPNMLISTVIEW)pnmh;
	int i = pnmv->iItem;

	if (LVIF_STATE != pnmv->uChanged)
		return FALSE;

	if ( !(pnmv->uNewState & (LVIS_FOCUSED | LVIS_SELECTED)) )
		return FALSE;

	i = pnmv->iItem;

	if (m_handles[i].is_valid() && m_strings[i] && *m_strings[i])
		uSetWindowText(uGetDlgItem(IDC_EDIT_PREVIEW), m_strings[i]);
	else
		uSetWindowText(uGetDlgItem(IDC_EDIT_PREVIEW), "");

	return FALSE;
}

LRESULT CTaggerDialog::OnLvnKeydownListFiles(int idCtrl, LPNMHDR pnmh, BOOL& bHandled)
{
	LPNMLVKEYDOWN pnkd = (LPNMLVKEYDOWN)pnmh;

	// Delete Key
	if (pnkd->wVKey == VK_DELETE)
	{
		DeleteSelected();

		return TRUE;
	}

	return FALSE;
}

LRESULT CTaggerDialog::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	// Do first DDX
	DoDataExchange();

	// Init the CDialogResize code
	DlgResize_Init();

	m_files.SetExtendedListViewStyle(LVS_EX_GRIDLINES | LVS_EX_FULLROWSELECT);

	// Add Columns
	m_files.InsertColumn(0, _T("File Name"), LVCFMT_LEFT, 340);
	m_files.InsertColumn(1, _T("-"), LVCFMT_CENTER, 80);

	// Add Items
	for (t_size i = 0; i < m_handles.get_count(); ++i)
	{	
		// File Name
		const metadb_handle_ptr & p = m_handles.get_item_ref(i);

		if (p.is_empty())
		{
			// Ignore
			continue;
		}

		tstring wstr;
		pfc::string8_fast tmp;
		pfc::string8_fast path = file_path_display(p->get_path());

		tmp.set_string(path.get_ptr() + scan_filename(path));

		// Check subsong index
		if (p->get_subsong_index() > 0)
		{
			tmp.add_string(" /index:");
			tmp.add_string(pfc::format_uint(p->get_subsong_index()));
		}

		wstr = pfc::stringcvt::string_os_from_utf8_fast(tmp);
		m_files.AddItem(i, 0, wstr.c_str());

		if (m_strings[i] && *m_strings[i])
			wstr = _T("<found>");
		else
			wstr = _T("<not found>");

		m_files.AddItem(i, 1, wstr.c_str());
		m_files.SetItemData(i, (DWORD_PTR)m_handles[i].get_ptr());
	}

	return TRUE; // set focus to default control
}

void CTaggerDialog::DeleteSelected()
{
	int index;
	while (-1 != (index = m_files.GetNextItem(-1, LVNI_SELECTED)))
	{
		// Add to skipped
		const metadb_handle * ptr = (const metadb_handle *)m_files.GetItemData(index);
		m_skipped.add_item(ptr);

		m_files.DeleteItem(index);
	}
}
